package com.ljyhhh.SmartCity.activity.listView

import android.content.Intent
import android.os.Bundle
import android.widget.ArrayAdapter
import androidx.appcompat.app.AppCompatActivity
import com.alibaba.fastjson.JSONObject
import com.ljyhhh.SmartCity.ItemAdapter
import com.ljyhhh.SmartCity.R
import com.ljyhhh.SmartCity.adapter.NewsItem
import kotlinx.android.synthetic.main.activity_net_request_list_view.*
import okhttp3.*
import okio.IOException


class ActivityNetRequestListView : AppCompatActivity() {


    val HOST="http://8.137.8.86"
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_net_request_list_view)
        initNews()

        }
        private fun initNews() {
            Thread{
                val okHttpClient = OkHttpClient()
                val request: Request = Request.Builder().url("http://8.137.8.86/api/message/list?category=MAJOR").build()

                okHttpClient.newCall(request).enqueue(object : Callback {
                    override fun onFailure(call: Call, e: IOException) {
                        // 处理错误
                    }

                    override fun onResponse(call: Call, response: Response) {

                        val res =response.body?.string()
                        val bodys1= mutableListOf<String>()
                        val news= mutableListOf<NewsItem>()
                        val root=JSONObject.parseObject(res)
                        val datas=root.getJSONArray("data")
                        for (i in 0 until datas.size){
                            val obj= datas[i] as JSONObject
                            bodys1.add(obj.getString("content"))
                            news.add(
                                NewsItem(HOST+obj.getString("preview"),
                                obj.getString("title")
                                )
                            )
                        }

                        runOnUiThread{

                            listA.adapter=ItemAdapter(application,R.layout.list_item,news)
                            listA.setOnItemClickListener { parent, view, position, id ->
                                when(position){
                                    else->{
                                        val intent=Intent(applicationContext, ActivityDisplay::class.java)
                                        intent.putExtra("body",bodys1[position])
                                        startActivity(intent)
                                    }
                                }


                            }
                        }

                    }
                })
            }.start()

    }

    }









